<template>

  <van-cell-group class="L-jhgl-box">
    <van-row type="flex" justify="space-between" align="center">
      <van-col>
        <span class="L-bold-text">
          目的:{{ planItem.jhgl_mudi }}
        </span>
      </van-col>
      <van-col style="text-align: right;">
        <span class="L-small-text">客户数量:{{ planItem.jhgl_khs }}</span>
      </van-col>
    </van-row>
    <van-divider />
    <van-row type="flex" justify="space-between">
      <van-col>
        <div class="L-small-text L-secondary-text-color">
          开始时间:{{ formatDate(planItem.jhgl_kssj) }}
        </div>
        <div class="L-small-text L-secondary-text-color">
          结束时间:{{ formatDate(planItem.jhgl_jssj) }}
        </div>
        <div class="L-small-text L-secondary-text-color">
          执行周期:{{ formatPeriod(planItem.jhgl_zqlxpq_enum, planItem.jhgl_zqlx_enum, planItem.jhgl_pqz) }}
        </div>
      </van-col>
      <van-col class="L-text-align-right">
        <div class="L-small-text">
          状态 : <span style="color:#ee8700">{{ planItem.jhgl_status_enum }}</span>
        </div>
        <div class="L-margin-top-20">
          <van-tag v-if="planItem.jhgl_jhscbylx_enum == '路线内'" style="margin-right:10px" color="#fbf1ec"
            text-color="#f57746" size="medium" round>路线</van-tag>
          <van-tag v-if="planItem.jhgl_zqlx_enum === '单次'" color="#fef6ec" text-color="#f56c6c" size="medium" round>
            {{ planItem.jhgl_zqlx_enum }} </van-tag>
          <van-tag v-if="planItem.jhgl_zqlx_enum === '周期'" color="#f0f9ec" text-color="#67c33a" size="medium" round>
            {{ planItem.jhgl_zqlx_enum }} </van-tag>
        </div>

      </van-col>
    </van-row>

    <van-divider />

    <van-row type="flex" justify="space-between" align="center">
      <van-col :span="8"><span class="L-small-text ">执行人: {{ planItem.jhgl_idowner_ref }}</span></van-col>
      <van-col :span="8"><span class="L-small-text ">创建人:{{ planItem.jhgl_createdby_ref }}</span></van-col>
      <van-col :span="8"><span class="L-small-text ">协防人: {{ planItem.jhgl_xiefangby_ref ? planItem.jhgl_xiefangby_ref
          :'无'}}</span></van-col>

    </van-row>
  </van-cell-group>

  <van-cell-group class="L-margin-top-20" style="padding: 10px">

    <div class="L-form-title-row">
      <div>
        <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
        <span class="L-text L-primary-text-color">客户列表</span>
      </div>
    </div>

    <div v-for="(item, index) in customerArr" :key="index">
      <van-row>
        <van-col :span="4" style="text-align: center;">
          <img src="@/assets/images/default_company.png" style="width: 40px;">
        </van-col>
        <van-col :span="16">
          <div class="L-text">{{ item.sname }}</div>
          <div class="L-mini-text L-secondary-text-color">{{ item.saddress }}</div>
        </van-col>
        <van-col :span="4" style="text-align: center;">
          <span style="color:#1c71fb;font-size:14px" @click="handleNavigation(item)">
            导航
            <!-- <i class="iconfont icon-daohang"></i> -->
          </span>
        </van-col>
      </van-row>
      <van-divider />
    </div>
  </van-cell-group>

  <div class="L-bottom-space"></div>

  <div class="L-bottom-row" v-if="operation.length > 0"
    :style="{ justifyContent: operation.length == 1 ? 'center' : 'space-evenly' }">
    <template v-for="(item, index) in operation" :key="index">
      <div class="L-operate-btn" @click="handleClickOperation(item)" v-if="index < 2">{{ item.title }}</div>
    </template>

    <van-popover v-model:show="showPopover" placement="top-end" :actions="operationMoreActions"
      @select="handleClickOperation">
      <template #reference>
        <div v-if="operation.length > 2" class="L-operate-more-btn">
          <i class="iconfont icon-icon_more L-title"></i>
        </div>
      </template>
    </van-popover>
  </div>

  <!-- 编辑弹窗 -->
  <!-- <van-popup v-model:show="showEditPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showEditPopup" :loadapi="editApi" :loadParams="editParams" :submitapi="editSubmitapi" :callBack="handleEditSubmit" mode="pop" :idobject="idobject"></Form>
  </van-popup> -->

  <!-- 地图弹窗 -->
  <van-popup round v-model:show="showeMapPopup" position="bottom" style="width: 100%;height:70%">
    <Map v-if="showeMapPopup" :map-data="currentMapInfo"></Map>
  </van-popup>
</template>

<script setup lang="ts">
import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();
import Map from "@/components/base/Map/Map.vue";
import { apiConfigurable } from "@/request/api/api";
import { ref, reactive, onMounted } from "vue";
import {
  closeToast,
  showLoadingToast,
  showConfirmDialog,
  showToast,
} from "vant";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

const idobject = ref("");
const itemid = ref("");
const idtemplate = ref("");

idobject.value = route.query.idobject as string;
itemid.value = route.query.itemid as string;
idtemplate.value = route.query.idtemplate as string;
// const item = JSON.parse(route.query.item);

import type { planItemVO } from "@/interface/interface"
const planItem = ref<planItemVO>({});
planItem.value = JSON.parse(route.query.item as string);



const operation = ref([]);
const operationMoreActions = ref([]);
const showPopover = ref(false);
const customerArr = ref([]);

const loading = ref(false);

interface params {
  [idx: string]: any;
}

onMounted(() => {
  getData();
});

function getData() {
  const { idobject, itemid, idtemplate } = route.query;
  const params: params = {};
  params[`${idobject}_id`] = itemid;
  params[`${idobject}_idtemplate`] = idtemplate;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  loading.value = true;
  const url = `${idobject}.check.do`;

  apiConfigurable(url, params).then(async (res) => {
    const jsondata = res.data.jsondata;
    const mxList = res.data.mxList;


    if (jsondata.operation) {
      operation.value = jsondata.operation || [];
      if (operation.value.length > 2) {
        operationMoreActions.value = operation.value
          .filter((item, index) => index > 1)
          .map((item) => {
            return { text: item.title, ...item };
          });
      }
    }

    if (mxList) {
      customerArr.value = res.data.mxList;
    }

    loading.value = false;
    closeToast();
  });
}

// 地图=============================
interface mapInfo {
  name: string;
  address: string;
  lat: string | number;
  lng: string | number;
}

const showeMapPopup = ref(false);
const currentMapInfo = reactive<mapInfo>({
  name: "",
  address: "",
  lat: "",
  lng: "",
});

function handleNavigation(item) {
  currentMapInfo.name = item.sname;
  currentMapInfo.address = item.saddress;
  // currentMapInfo.lat = item.lonlat.split(",")[1];
  // currentMapInfo.lng = item.lonlat.split(",")[0];
  showeMapPopup.value = true;
}

function formatPeriod(pqlx: string, zqlx: string, pqz: string) {
  if (zqlx == "周期") {
    if (pqlx == "按周排期") {
      return "每周 周" + pqz;
    }
    return "每月 " + pqz;
  }
  return "无";
}

function formatDate(dateString: string) {
  if (!dateString) return "";
  const date = new Date(dateString);

  enum yearVO {
    numeric="numeric",
    digit="2-digit"
  }

  enum monthVO {
    numeric="numeric",
    digit="2-digit",
    long="long",
    short="short",
    narrow="narrow",

  }


  const options = {
    year: yearVO.numeric,
    month: monthVO.long,
    day: yearVO.numeric,
    timeZone: "Asia/Shanghai",
  };
  return date
    .toLocaleDateString("zh-CN", options)
    .replace(/年(\d{1,2})月/, "年$1月")
    .replace(/日$/, "日");
}

function handleClickOperation(action) {
  console.log("action", action);
  const { mobileFunc } = action;
  switch (mobileFunc) {
    case "edit":
      toEdit();
      break;
    case "del":
      handleDel();
      break;
    case "audit":
      handleAudit();
      break;

    case "unaudit":
      handleUnaudit();
      break;

    case "start":
      handleStart();
      break;
    case "stop":
      handleStop();
      break;

    case "finish":
      handleFinish();
      break;
  }
}

//编辑
const showEditPopup = ref(false);
const editApi = ref("");
const editSubmitapi = ref("");
const editParams = reactive<params>({});

function toEdit() {
  const { idobject, idtemplate, stitle, itemid } = route.query;

  const path = `/jhglForm`
  const { jhgl_jhcj_ref, jhgl_jhcj } = planItem.value;

  const query = {
    itemid,
    idobject,
    idtemplate,
    scenarioId: jhgl_jhcj,
    scenarioTitle: jhgl_jhcj_ref,
  };

  router.replace({
    path,
    query,
  });
  // showEditPopup.value = true;
  // const { idobject, itemid } = route.query;
  // editApi.value = `${idobject}.edit.do`;
  // editSubmitapi.value = `${idobject}.editsave.do`;
  // editParams[`${idobject}_id`] = itemid;
}


//开始
function handleStart() {

  // console.log("^^^^",planItem.value)
  // return 
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + '_status']: planItem.value[`${realObj}_status`],
    [realObj + '_status_enum']: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId
  };
  const url = realObj + ".start.do";

  operateApi(url, data)
}

//停止
function handleStop() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + '_status']: planItem.value[`${realObj}_status`],
    [realObj + '_status_enum']: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId
  };
  const url = realObj + ".stop.do";

  operateApi(url, data)
}

//结束
function handleFinish() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + '_status']: planItem.value[`${realObj}_status`],
    [realObj + '_status_enum']: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId
  };
  const url = realObj + ".finish.do";

  operateApi(url, data)
}
//删除
function handleDel() {
  const { itemid, idobject } = route.query;
  showConfirmDialog({
    title: "标题",
    message: "确认要删除当前数据吗?",
  }).then(() => {
    const realObj = idobject;
    const realId = itemid;
    const data = { [realObj + "_id"]: realId };
    const url = realObj + ".del.do";

    operateApi(url, data)
  });
}
//审核
function handleAudit() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".audit.do";

  operateApi(url, data)
}
//弃审
function handleUnaudit() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".unaudit.do";
  operateApi(url, data)
}

//执行操作接口
function operateApi(url, data) {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(url, data).then((res) => {
    showToast("操作成功");
    setTimeout(() => {
      routerStore.mode = "reload";
      router.go(-1)

    }, 1000);
  });

}
</script>

<style scoped>
.L-jhgl-box {
  padding: 15px;
}
</style>